package com.sc.syllabus.decoration;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.sc.syllabus.R;
import com.sc.syllabus.decoration.bean.HouseDecorationBean;
import com.sc.syllabus.model.TypeId;
import com.sc.syllabus.utils.IPopupSelectListener;
import com.sc.syllabus.utils.PopupListUtils;
import com.sc.syllabus.view.SegmentControl;
import com.srain.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by liushuanglong on 2017/9/20.
 */
public class DecorationListActivity extends Activity implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = "DecorationListActivity";

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, DecorationListActivity.class));
    }

    private ListView listView;
    private SegmentControl segment;
    private TextView text, textType;
    private int mSegmentIndex = 0;
    private DecorationListAdapter adapter;
    private List<HouseDecorationBean> data = new ArrayList<HouseDecorationBean>();
    private DecorationModelImpl mModel;
    private int mType = 0; // 分类标识

    private static final String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_decorations);
        boolean hasPermis = EasyPermissions.hasPermissions(DecorationListActivity.this, PERMISSIONS_STORAGE);
        LogUtils.e(TAG, "updatePosition --- hasPermis == " + hasPermis);
        if (hasPermis) {
            mModel = DecorationModelImpl.getInstance(this);
        } else {
            EasyPermissions.requestPermissions(this, "申请权限", 110, PERMISSIONS_STORAGE);
        }
        initView();
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.listview);
        listView.setOnItemClickListener(mItemClickListener);
        listView.setOnItemLongClickListener(mItemLongClickListener);
        segment = (SegmentControl) findViewById(R.id.segment_control);
        segment.setOnSegmentControlClickListener(mSegmentClickListener);
        textType = (TextView) findViewById(R.id.text_type);
        text = (TextView) findViewById(R.id.text);
        textType.setOnClickListener(mClickListener);
        text.setOnClickListener(mClickListener);
        adapter = new DecorationListAdapter(DecorationListActivity.this, data);
        listView.setAdapter(adapter);
    }

    private View.OnTouchListener mTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (v.getId()) {
                case R.id.text:
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        LogUtils.e(TAG, "onTouchListener --- MotionEvent.ACTION_DOWN --- " + System.currentTimeMillis());
                        Message msg = mHandler.obtainMessage(0);
                        mHandler.sendMessageDelayed(msg, 1500);
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        LogUtils.e(TAG, "onTouchListener --- MotionEvent.ACTION_UP --- " + System.currentTimeMillis());
                    }
                    break;
            }
            return true;
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    LogUtils.e(TAG, "onTouchListener --- mHandler --- msg.what == 0 --- " + System.currentTimeMillis());
                    EditDecorationActivity.actionStart(DecorationListActivity.this);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        segment.setSelectedIndex(0);
    }

    private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HouseDecorationBean bean = data.get(position);
            if (null != bean) {
                LogUtils.i(TAG, "ItemClick --- bean == " + bean.toString());
                EditDecorationActivity.actionStart(DecorationListActivity.this, bean);
            }
        }
    };

    private AdapterView.OnItemLongClickListener mItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            HouseDecorationBean bean = data.get(position);
            if (null != bean) {
                int beanId = mModel.deleteByObject(bean);
                LogUtils.e(TAG, "mItemLongClickListener --- beanId == " + beanId);
                if (beanId > 0) {
                    adapter.remove(position);
                }
            }
            return true;
        }
    };

    private SegmentControl.OnSegmentControlClickListener mSegmentClickListener = new SegmentControl.OnSegmentControlClickListener() {

        @Override
        public void onSegmentControlClick(int index) {
            mSegmentIndex = index;
            switch (index) {
                case 0:
                    textType.setVisibility(View.GONE);
                    break;
                default:
                    textType.setVisibility(View.VISIBLE);
                    break;
            }
            search();
        }
    };

    private View.OnClickListener mClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.text:
                    EditDecorationActivity.actionStart(DecorationListActivity.this);
                    break;

                case R.id.text_type:
                    PopupListUtils popup = new PopupListUtils(DecorationListActivity.this, R.id.layout, TypeId.typeTitles);
                    popup.setSelect(mType);
                    popup.registSelectListener(mPopupListener);
                    popup.show();
                    break;
            }
        }
    };

    private IPopupSelectListener mPopupListener = new IPopupSelectListener() {
        @Override
        public void updateTitle(String title) {
            textType.setText(title);
        }

        @Override
        public void updatePosition(int position) {
            mType = position;
            search();
        }
    };

    private void search() {
        String orderBy = "type";
        WhereBuilder whereBuilder = new WhereBuilder(HouseDecorationBean.class);
        if (0 != mSegmentIndex) {
            whereBuilder.equals("type", mType);
        }
        switch (mSegmentIndex) {
            case 0:
                break;

            case 1:
                whereBuilder.andEquals("actualNum", 0);
                break;

            case 2:
                whereBuilder.greaterThan("actualNum", 0);
                break;
        }

        QueryBuilder builder = new QueryBuilder(HouseDecorationBean.class)
                .where(whereBuilder)
                .distinct(true);
        if (!TextUtils.isEmpty(orderBy)) {
            builder.orderBy(orderBy);
        }

        data = mModel.queryByBuilder(builder);
        adapter.setData(data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        LogUtils.e(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        LogUtils.e(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
    }
}
